package com.fms.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fms.common.vo.Result;
import com.fms.sys.entity.Notice;
import com.fms.sys.service.INoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Jinfeng
 * @since 2023-03-18
 */
@RestController
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private INoticeService noticeService;

    @GetMapping("/list")
    public Result<Map<String, Object>> getNoticeList(
            @RequestParam(value = "pageNo", defaultValue = "1") Long pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") Long pageSize) {

        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Notice::getIssueTime);

        Page<Notice> page = new Page<>(pageNo, pageSize);
        noticeService.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> addNotice(@RequestBody Notice notice) {
        noticeService.save(notice);
        return Result.success("新增公告成功");
    }

    @PutMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> updateNotice(@RequestBody Notice notice) {
        noticeService.updateById(notice);
        return Result.success("修改公告成功");
    }

    @GetMapping("/{id}")
    public Result<Notice> getNoticeById(@PathVariable("id") Long id) {
        Notice notice = noticeService.getById(id);
        if (notice == null) {
            return Result.fail("公告不存在");
        }
        return Result.success(notice);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<?> deleteNoticeById(@PathVariable("id") Long id) {
        if (!noticeService.removeById(id)) {
            return Result.fail("删除失败，公告不存在");
        }
        return Result.success("删除公告成功");
    }
}
